package com.tarena.lbs.attach.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarena.lbs.attach.dao.mapper.AttachMapper;
import com.tarena.lbs.attach.dao.repository.AttachRepository;
import com.tarena.lbs.attach.pojo.po.AttachPO;
import com.tarena.lbs.attach.pojo.vo.FileVO;
import com.tarena.lbs.attach.service.AttachService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class AttachServiceImpl extends ServiceImpl<AttachMapper,AttachPO> implements AttachService {
    @Autowired
    private AttachRepository attachRepository;
    private static final String UPLOAD_DIR = "uploads";


    @Override
    public FileVO uploadFile(MultipartFile file) throws IOException {
        log.debug("文件上传={}",file);
        //1.获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();
        //2.获取文件的扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.生成唯一的文件名
        String uniqueFilename = UUID.randomUUID().toString() + extension;
        //4.指定一个文件夹用于保存上传的文件
        String dirPath = "d:/files";
        //5.为了提高检索性能,可以将文件存入以日期为分层的多层文件夹中
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        //6.将当前日期转换为上面格式的字符串
        String datePath = sdf.format(new Date());
        //7.拼接完整的文件夹路径,并创建Java的File对象
        File dirFile = new File(dirPath+datePath);
        //8.继续使用文件类的API创建多层文件夹
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+datePath+uniqueFilename;
        file.transferTo(new File(filePath));

        FileVO fileVO = new FileVO();
        fileVO.setFileUuid(uniqueFilename);
        fileVO.setUrl(filePath);
        AttachPO attachPO = new AttachPO();
        BeanUtils.copyProperties(fileVO,attachPO);
        attachRepository.save(attachPO);

        return fileVO;
    }
}
